package huanzhao.erp.other.config;

import cn.dev33.satoken.interceptor.SaInterceptor;
import cn.dev33.satoken.stp.StpUtil;
import huanzhao.erp.other.interceptor.GlobalInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @author April
 * @version 1.0
 */
@Configuration
public class MvcConfig implements WebMvcConfigurer {
    private final ProjectConfig projectConfig;

    public MvcConfig(ProjectConfig projectConfig) {
        this.projectConfig = projectConfig;
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 注册全局拦截器
        if (projectConfig.getOpenLog()) {
            registry.addInterceptor(new GlobalInterceptor()).addPathPatterns("/**").excludePathPatterns("/druid/**");
        }
        // 注册登录拦截器
        registry.addInterceptor(new SaInterceptor(handle -> StpUtil.checkLogin())).
                addPathPatterns("/api/process/**").
                addPathPatterns("/api/team/**").
                addPathPatterns("/api/staff").
                addPathPatterns("/api/subscribe").
                addPathPatterns("/api/notification/**").
                addPathPatterns("/api/logout").
                addPathPatterns("/api/barcode/*").
                excludePathPatterns("/api/process/phones");
    }


    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        StringHttpMessageConverter stringConverter = new StringHttpMessageConverter(StandardCharsets.UTF_8);
        stringConverter.setWriteAcceptCharset(false);
        converters.add(stringConverter);
    }
}
